package com.example.lenovo.weiyi;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.com.ruanmeng.demon.LoginM;
import com.com.ruanmeng.demon.VersionM;
import com.com.ruanmeng.utils.CommonUtil;
import com.com.ruanmeng.utils.Params;
import com.com.ruanmeng.utils.PreferencesUtils;
import com.com.ruanmeng.utils.UpdateService;
import com.com.ruanmeng.view.PopupWindowUpdateUtils;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import butterknife.BindView;
import butterknife.ButterKnife;
import nohttp.CallServer;
import nohttp.CustomHttpListener;
import share.Const;
import share.HttpIP;

/**
 * 强制登陆才能进入首页
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_user_name)
    EditText etUserName;
    @BindView(R.id.et_user_psw)
    EditText etUserPsw;
    @BindView(R.id.cb_is_visible)
    CheckBox cbIsVisible;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.login_line)
    View loginLine;
    @BindView(R.id.iv_login_user_name)
    ImageView ivLoginUserName;
    private VersionM modelver;
    private boolean isForce = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        AddLoginActivity(this);
        checkReadPermission();
        init();
        if (Params.getversion == 0) {
            Params.getversion = 1;
            getVersionData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(PreferencesUtils.getString(LoginActivity.this, "phone"))) {
            etUserName.setText(PreferencesUtils.getString(LoginActivity.this, "phone"));
        }
    }

    public void init() {
        if (PreferencesUtils.getInt(LoginActivity.this, "Login") == 1 && ("1").equals(PreferencesUtils.getString(LoginActivity.this, "statues"))) {
            Intent in = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(in);
            finish();
        }
        if (PreferencesUtils.getInt(LoginActivity.this, "Login") == 1 && !("1").equals(PreferencesUtils.getString(LoginActivity.this, "statues"))) {
            Intent in = new Intent(LoginActivity.this, MustSetPerMessActivity.class);
            startActivity(in);
            finish();
        }
        btLogin.setClickable(false);
        etUserName.addTextChangedListener(this);
        etUserPsw.addTextChangedListener(this);
        setlistener();
    }

    public void setlistener() {
        etUserName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        super.onTextChanged(charSequence, i, i1, i2);
        if (CommonUtil.getEditText(etUserName).isEmpty() || CommonUtil.getEditText(etUserPsw).isEmpty()) {
            btLogin.setBackgroundResource(R.drawable.ed_fullgeray);
            btLogin.setClickable(false);
        }
        if (CommonUtil.getEditText(etUserName).isEmpty() == false && CommonUtil.getEditText(etUserPsw).isEmpty() == false) {
            btLogin.setBackgroundResource(R.drawable.ed_fullmain);
            btLogin.setClickable(true);
        }
        //密码是否可见
        if (CommonUtil.getEditText(etUserPsw).isEmpty()) {
            cbIsVisible.setVisibility(View.GONE);
        } else {
            cbIsVisible.setVisibility(View.VISIBLE);
        }
        if (etUserName.getText().toString().length() > 0) {
            ivLoginUserName.setVisibility(View.VISIBLE);
        } else {
            ivLoginUserName.setVisibility(View.GONE);
        }

    }

    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.tv_fast_register://注册
                startActivity(RegisterPhoneActivity.class);
                break;
            case R.id.tv_forget_psw://忘记密码
                Intent in = new Intent(LoginActivity.this, RegisterPhoneActivity.class);
                in.putExtra("forget", "1");
                startActivity(in);
                break;
            case R.id.bt_login://登陆
                getLoginData();
                break;
            case R.id.cb_is_visible://密码是否可见
                if (cbIsVisible.isChecked()) {
                    etUserPsw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etUserPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                break;
            case R.id.iv_login_user_name:
                etUserName.setText("");
                break;

        }
    }

    /**
     * 完成并登陆
     */
    public void getLoginData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.Login, Const.POST);
        mRequest.add("accountName", etUserName.getText().toString());
        mRequest.add("password", etUserPsw.getText().toString());
        // 添加到请求队列
        CallServer.getRequestInstance().add(LoginActivity.this, 0, mRequest,
                new CustomHttpListener(LoginActivity.this, true, LoginM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        LoginM model = ((LoginM) data);
                        PreferencesUtils.putString(LoginActivity.this, "phone", etUserName.getText().toString());
                        PreferencesUtils.putString(LoginActivity.this, "psw", etUserPsw.getText().toString());
                        PreferencesUtils.putString(LoginActivity.this, "uid", model.getObject().getToken());
                        PreferencesUtils.putString(LoginActivity.this, "url", model.getObject().getUserhead());
                        PreferencesUtils.putString(LoginActivity.this, "statues", model.getObject().getStatus());
                        PreferencesUtils.putString(LoginActivity.this, "weight", model.getObject().getWeight());
                        PreferencesUtils.putString(LoginActivity.this, "stature", model.getObject().getStature());
                        PreferencesUtils.putString(LoginActivity.this, "age", model.getObject().getAge() + "");
                        if (model.getObject().getStatus() != null && ("1").equals(model.getObject().getStatus())) {//不用再强制补充个人资料
                            PreferencesUtils.putString(LoginActivity.this, "user_name", model.getObject().getUserName());
                            PreferencesUtils.putInt(LoginActivity.this, "Login", 1);//登陆标记
                            Params.ToSy = 1;
                            Intent in = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(in);

                        } else {
//                            ShowPop();
                            Intent in = new Intent(LoginActivity.this, MustSetPerMessActivity.class);
                            startActivity(in);
                        }
                        finish();
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                        if (!("100").equals(obj.getString("msgcode"))) {
                            CommonUtil.showToask(LoginActivity.this, obj.getString("msg"));
                        }
                    }
                }, true, true);
    }

    /**
     * 重写返回键事件
     */

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            clearActivity();
            clearLoginActivity();
            clearMainActivity();
            finish();
            System.exit(0);
        }
        return false;
    }

    /**
     * 强制完善个人资料
     */
    public void ShowPop() {
        // 加载布局
        LayoutInflater inflater = LayoutInflater
                .from(LoginActivity.this);
        View view = inflater.inflate(R.layout.dialog_mustlayout, null);
        TextView tv_must_sure = (TextView) view.findViewById(R.id.tv_must_sure);
        // 创建popupwindow对话框
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setFocusable(true);// 必须有，因为要获得焦点进行输入
        // 设置此参数，点击外边可消失
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 点击其他除了popupwindow对话框的地方就可使popupwindow对话框消失
        pop.setOutsideTouchable(true);
        //pop.showAtLocation(liFr, Gravity.CENTER, 0, 0);// 显示位置以某控件为中心
        if (Build.VERSION.SDK_INT >= 24) {
            int[] a = new int[2];
            loginLine.getLocationInWindow(a);
            pop.showAtLocation((LoginActivity.this).getWindow().getDecorView(), Gravity.NO_GRAVITY, 0, a[1] + loginLine.getHeight());
        } else {
            pop.showAsDropDown(loginLine);
        }
        tv_must_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 请求接口
                pop.dismiss();
                Intent in = new Intent(LoginActivity.this, MustSetPerMessActivity.class);
                startActivity(in);
            }
        });
    }
    public void getVersionData() {
        Request<String> mRequest = NoHttp.createStringRequest(HttpIP.UpdateVersion, Const.POST);
        // 添加到请求队列
        CallServer.getRequestInstance().add(LoginActivity.this, 0, mRequest,
                new CustomHttpListener(LoginActivity.this, true, VersionM.class) {
                    @Override
                    public void doWork(Object data, boolean isOne) {
                        modelver = ((VersionM) data);
                        if (getVersionName(LoginActivity.this).equals(modelver.getObject().getVersionNo())) {
//                            CommonUtil.showToask(MainActivity.this, "当前已是最新版本");
                        } else {
                            if (!TextUtils.isEmpty(modelver.getObject().getForce())) {
                                String a = modelver.getObject().getForce();
                                if (a.equals("1")) {//强制
                                    isForce = true;
                                    PopupWindowUpdateUtils.getInstance().getSmartUpdateDialog(LoginActivity.this, modelver.getObject().getContent(), modelver.getObject().getTitle(), new PopupWindowUpdateUtils.PopupYearWindowCallBack() {
                                        @Override
                                        public void doWork() {
                                            downLoadApk(modelver.getObject().getUrl());
                                        }

                                        @Override
                                        public void doBack() {

                                        }
                                    });
                                } else {//非强制
                                    isForce = false;
                                    showData(modelver, true);
                                }
                            } else {//非强制
                                isForce = false;
                                showData(modelver, true);
                            }
//                            Version();
                        }
                    }

                    @Override
                    public void onFinally(JSONObject obj) throws JSONException {
                        super.onFinally(obj);
                    }
                }, true, false);
    }

    /**
     * 版本名
     */
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    /**
     * 版本更新
     */
    public void Version() {
        // 解析xml
        View view = View.inflate(LoginActivity.this,
                R.layout.setting_custom_dialog, null);
        TextView text_dialog = (TextView) view.findViewById(R.id.text_dialog);
        text_dialog.setText("检测到新版本，是否更新？");
        // 对话框
        final Dialog dialog = new AlertDialog.Builder(LoginActivity.this)
                .create();
        dialog.show();
        dialog.getWindow().

                setContentView(view);

        // 取消按钮
        TextView btn_Cancel = (TextView) view.findViewById(R.id.cancle);
        btn_Cancel.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              dialog.dismiss();
                                          }
                                      }

        );
        // 确定按钮
        TextView btn_OK = (TextView) view.findViewById(R.id.sure);
        btn_OK.setOnClickListener(new View.OnClickListener() {
                                      @Override
                                      public void onClick(View v) {
                                          dialog.dismiss();
                                          Intent intent1 = new Intent();
                                          intent1.setClass(LoginActivity.this, UpdateService.class);
                                          intent1.putExtra("versionCode", modelver.getObject().getVersionNo());
                                          intent1.putExtra("url", modelver.getObject().getUrl());
                                          LoginActivity.this.startService(intent1);
                                      }
                                  }

        );


    }

    /*
       * 从服务器中下载APK
       */
    Handler handler_Delay = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    getVersionData();
                    break;
            }
        }
    };

    protected void downLoadApk(final String path) {
        final ProgressDialog pd;    //进度条对话框
        pd = new ProgressDialog(LoginActivity.this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keycode, KeyEvent keyEvent) {
                if ((keycode == KeyEvent.KEYCODE_BACK)) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (isForce) {
                    handler_Delay.sendEmptyMessageDelayed(1, 2000);
                }
            }
        });
        pd.setMessage("正在下载更新...");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(path, pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                    isLoad = false;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private boolean isExistSd() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    private boolean isLoad = false;

    /*
  * 从服务器下载apk
  */
    public File getFileFromServer(String path, ProgressDialog pd) throws Exception {
        //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (isExistSd()) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            long fileLength = conn.getContentLength();
            conn.setConnectTimeout(5000);
            //获取到文件的大小
//            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "working.apk");// Environment.getExternalStorageDirectory().getAbsolutePath()
            if (!file.getParentFile().exists()) {
                // 分两次mkdirs，是为了避免目录层级过高导致目录创建失败的情况
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                //获取当前下载量
                int curProgress = (int) (((float) total / fileLength) * 100);
                pd.setProgress(curProgress);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 执行的数据类型
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            startActivity(intent);
        } else {//7.0
//            Uri apkUri =
//                    FileProvider.getUriForFile(this, "com.ruanmeng.daddywashing_delivery.fileprovider", file);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//            Uri apkUri =
//                    FileProvider.getUriForFile(this, "com.ruanmeng.weiyi.provider", file);
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "applicationnd.android.package-archive");
            Uri apkUri = FileProvider.getUriForFile(this, "com.ruanmeng.weiyi.provider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClassName("com.android.packageinstaller", "com.android.packageinstaller.PackageInstallerActivity");
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            startActivity(install);
        }

    }

    /**
     * 更新版本
     *
     * @param dataM
     */
    private void showData(final VersionM dataM, boolean isUp) {
        try {
            PopupWindowUpdateUtils.getInstance().getUpdateDialog(this, new PopupWindowUpdateUtils.PopupYearWindowCallBack() {
                @Override
                public void doWork() {
                    downLoadApk(dataM.getObject().getUrl());
                }

                @Override
                public void doBack() {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //关于系统6.0以上的权限适配注意Manifest的导包  读写权限
    private void checkReadPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                // 是否需要弹出一个解释申请该权限的提示给用户，如果为true，则可以弹。
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(LoginActivity.this, "没权限", Toast.LENGTH_SHORT).show();
                    ActivityCompat.requestPermissions(
                            LoginActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            0);
                } else {

                    // 在Fragment中申请权限，不要使用ActivityCompat.requestPermissions,
                    // 直接使用Fragment的requestPermissions方法，否则会回调到Activity的 onRequestPermissionsResult
                    ActivityCompat.requestPermissions(
                            LoginActivity.this,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            0);

                    // Const.LOCATION_REQUEST is an app-defined int constant.
                    // The callback method gets the result of the request.
                }

            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                } else {
                    Toast.makeText(this, "请求权限被拒绝，请重新开启权限", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}
